package com.kotodama.infrastructure.tenant.filter;

import com.kotodama.infrastructure.tenant.context.TenantContext;
import com.kotodama.infrastructure.tenant.resolver.TenantResolverChain;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 租户标识过滤器
 * 在请求处理早期调用租户解析链，并将解析到的租户ID存入TenantContext
 */
@Component
@Order(1) // 确保在其他过滤器之前执行
public class TenantIdentifierFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(TenantIdentifierFilter.class);
    private static final String DEFAULT_TENANT_ID = "default";

    private final TenantResolverChain tenantResolverChain;

    public TenantIdentifierFilter(TenantResolverChain tenantResolverChain) {
        this.tenantResolverChain = tenantResolverChain;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        if (!(request instanceof HttpServletRequest httpRequest)) {
            chain.doFilter(request, response);
            return;
        }

        try {
            // 解析租户ID
            String tenantId = tenantResolverChain.resolveTenantId(httpRequest);

            // 如果无法解析租户ID，使用默认租户
            if (tenantId == null || tenantId.trim().isEmpty()) {
                tenantId = DEFAULT_TENANT_ID;
                logger.debug("未能解析租户ID，使用默认租户: {}", tenantId);
            } else {
                logger.debug("解析到租户ID: {}", tenantId);
            }

            // 设置租户上下文
            TenantContext.setTenantId(tenantId);

            // 继续处理请求
            chain.doFilter(request, response);

        } finally {
            // 请求完成后清理租户上下文
            TenantContext.clear();
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("租户标识过滤器初始化完成");
    }

    @Override
    public void destroy() {
        logger.info("租户标识过滤器销毁");
    }
}